<template>
  <div class="mc-image-net-upload">
      <!-- 增加编辑器内的体验 -->
      <el-upload v-if="canUpload" :file-list="fileList" v-bind="$attrs" v-on="$listeners" :action="uploadUrl"
      :on-preview="viewPic" :on-remove="removePic"  :list-type="listType">
          <i class="el-icon-upload" v-if="mcShowUploadIcon"></i>
      </el-upload>
      <el-upload disabled v-else :file-list="fileList" v-bind="$attrs" v-on="$listeners" :action="uploadUrl"
      :on-preview="viewPic" :on-remove="removePic" :list-type="listType">
          <i @click="assist" class="el-icon-upload" v-if="mcShowUploadIcon"></i>
      </el-upload>
      <el-button @click="openFileChooser"><i style="cursor:pointer" class="el-icon-platform-eleme" title="局域网上传"></i><slot></slot></el-button>
      <mc-dialog :visible.sync="chooseLocalFileVisible"  :modal="false">
            <mc-file-chooser @choose="chooseLocalFile" :data="mcChooserRoot" :mc-url="proxyDomain+'api/file/tree'"></mc-file-chooser>
      </mc-dialog>

      <mc-dialog :visible.sync="dialogVisible"  :modal="false" top="10px" width="80%">
        <img width="100%" height="100%" :src="dialogImageUrl" alt="">
      </mc-dialog>
  </div>
</template>

<script>
import McDialog from "./McDialog.vue";
import mcFileChooser from "./McFileChooser.vue"
export default {
    name: 'mc-image-net-upload',
    data () {
        return {
            //实现了双向绑定 坑爹的 不给值就报空指针
            fileList : this.buildFileList(this.value),
            dialogVisible:false,
            dialogImageUrl:"",
            uploadUrl: this.action||"",
            canUpload:window.iframeUi?false:true,
            chooseLocalFileVisible:false
        }
    },
    components:{
      McDialog,
      mcFileChooser
    },
    props:{
        /*自动计算服务名*/
        'mcCalcCtx':{type:Boolean,default:true},
        'action':{type:String,default:""},
        //此处的value 就是父亲的v-model
        'value' : {type:String},
        'listType': {type:String,default:'picture-card'},
        //是否显示上传图标
        'mcShowUploadIcon':{type:Boolean,default:true},
        //是否单文件模式，后面上传的都覆盖
        'mcSingleFile':{type:Boolean,default:false},
        /* 代理的域名 */
        'proxyDomain':{type:String,default:""},
        /* 根目录 */
        'mcChooserRoot':{type:String,default:""},
        //地址增加http前缀
        'mcUrlAbsolute':{type:Boolean,default:true},
    },
    watch:{
        //发现变更，把父组件的v-model给改变
        fileList(newValue){
            var arr = [];
            if(newValue){
                for(var i=0;i<newValue.length;i++){
                    var shortUrl = newValue[i].shortUrl;
                    var url = newValue[i].url;
                    if(this.mcUrlAbsolute){
                        arr.push(url);
                    }else{
                        arr.push(shortUrl);
                    }
                }
            }
            var url = arr.join(",")
            this.$emit("input",url)
        },
        value(newValue){
            this.fileList = this.buildFileList(newValue)
        }
    },
    mounted () {
        if(window.iframeUi&&window.iframeUi.jsonFactory){
          this.$nextTick(function(){
                var dragMcPane = window.iframeUi.jsonFactory.api().pubGetDragMcPaneName();
                var magicalCoderIdAttrName = window.iframeUi.jsonFactory.api().getMagicalCoderIdAttrName();
                var container = $("#magicalDragSceneGhost").length>0?$("#magicalDragSceneGhost") : $("#magicalDragScene");
                container.find(".mc-image-upload").each(function(idx,item){
                    var firstDiv = $(this).children().first();
                    if(firstDiv.length>0){//elementui 你为啥开始不创建这个结构烦死
                        firstDiv.removeAttr(magicalCoderIdAttrName);
                    }
                })
            //虚拟dom转化为真实dom后触发 这样动态新增的结构里 仍然可以被拖拽
              //window.iframeUi.magicalApi.addApiTask({methodName:"refreshDragEvent"});
          })
      }
    },
    methods:{
        buildShortUrl(url){
            if(url.startsWith("http")){
                return url;
            }
            var arr = url.split("\\");
            for(var i=0;i<arr.length;i++){
                if(arr[i]){
                    arr.splice(i,1);;
                    break;//找到第一个局域网名称 去掉返回
                }else{
                    arr.splice(i,1);
                    i--;
                }
            }
            var newUrl = "upload/"+arr.join("/");
            if(this.mcUrlAbsolute){
              return this.shortToFullUrl(newUrl);
            }
            return newUrl;
        },
        shortToFullUrl(shortUrl){
            if(shortUrl.startsWith("http")){
                return shortUrl;
            }
            if(!this.mcUrlAbsolute){
              return shortUrl;
            }
            return this.proxyDomain+shortUrl;
        },
        openFileChooser(){
            this.chooseLocalFileVisible = true;
        },
        chooseLocalFile({file}){
            var data = {};
            data.shortUrl = this.buildShortUrl(file);
            data.url = this.shortToFullUrl(data.shortUrl);
            data.name = this.getFileName(data.url);
            if(this.mcSingleFile){
                this.fileList=[data];
            }else {
                this.fileList.push(data);
            }
            this.$nextTick(()=>{
                //新的
                this.$emit("change",{value:this.value});
            })
            this.chooseLocalFileVisible = false;
        },
        assist(){
            this.$notify({type:"warning",message:"设计阶段暂停上传，您可以在预览界面体验",position:"bottom-right"})
        },
        getFileName(url){
            if(url){
                var pos1 = url.lastIndexOf('/');
                var pos2 = url.lastIndexOf('\\');
                var pos  = Math.max(pos1, pos2)
                if( pos<0 )
                    return url;
                else
                    var name = url.substring(pos+1);
                    if(name.indexOf("?")!=-1){
                        return name.split("?")[0];
                    }
                    return name;
            }
            return "";
        },
        buildFileList:function(v){
            var list = [];
            if(v){
                var arr = v.split(",");
                for(var i=0;i<arr.length;i++){
                    var shortUrl = arr[i];
                    var url = this.shortToFullUrl(shortUrl);
                    list.push({name:this.getFileName(url),url:url,shortUrl:shortUrl});
                }
            }
            return list;
        },
        viewPic:function(file){
            this.dialogImageUrl = file.url;
            this.dialogVisible = true;
        },
        removePic:function(file, fileList){
            var uid = file.uid;
            this.fileList = fileList;
            this.$nextTick(()=>{
                this.$emit("change",{value:this.value});
            })
        }
    }
}
</script>

<style lang="scss">
.mc-image-net-upload>div>.el-upload--picture-card{
    width:100%;
    height:100%;
    display:flex;
    align-items:center;
    justify-content:center;
}
.mc-image-net-upload>div:not(.el-dialog__wrapper){
    height:100%;
    /* width: 100%; */
}
.mc-image-net-upload div.el-upload{
    display: none;
}

</style>
